<?php

namespace Database\Seeders;

use App\Models\Room;
use App\Models\RoomMember;
use App\Models\User;
use App\Models\Menu;
use App\Services\DishService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class RoomSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 清空房间相关表（使用delete而不是truncate避免外键约束问题）
        DB::table('room_members')->delete();
        DB::table('rooms')->delete();
        
        // 获取所有用户
        $users = User::all();
        
        if ($users->isEmpty()) {
            $this->command->warn('没有用户数据，请先运行 UserSeeder');
            return;
        }
        
        // 获取可用的菜单
        $menus = Menu::where('is_public', true)->get();
        
        // 房间标题模板
        $roomTitles = [
            '美食聚餐', '朋友聚会', '家庭聚餐', '同事聚餐', '生日聚餐',
            '节日聚餐', '周末聚餐', '庆祝聚餐', '商务聚餐', '同学聚餐',
        ];
        
        // 创建20个房间
        for ($i = 1; $i <= 20; $i++) {
            $creator = $users->random();
            $roomType = rand(1, 10) <= 7 ? 'temporary' : 'permanent'; // 70%临时房间
            $menuSource = ['default', 'custom'][rand(0, 1)]; // 只有两种菜单来源
            
            // 选择菜单
            $selectedMenu = null;
            if ($menuSource === 'custom' && $menus->isNotEmpty()) {
                $selectedMenu = $menus->random();
            }
            
            // 生成房间数据
            $room = Room::create([
                'room_id' => Room::generateRoomId(),
                'title' => $roomTitles[array_rand($roomTitles)] . ($i > 10 ? ' ' . $i : ''),
                'description' => '一起来享受美食的乐趣吧！',
                'type' => $roomType,
                'creator_id' => $creator->id,
                'menu_source' => $menuSource,
                'menu_id' => $selectedMenu ? $selectedMenu->id : null,
                'settings' => [
                    'allowParticipantAdd' => true,
                    'allowParticipantSuggest' => true,
                    'showUserFavorites' => true,
                ],
                'expires_at' => $roomType === 'temporary' ? Carbon::now()->addDays(rand(1, 7)) : null,
                'status' => 'active',
                'max_participants' => rand(5, 20),
                'current_round' => 1,
                'total_orders' => rand(0, 50),
                'last_activity_at' => Carbon::now()->subMinutes(rand(0, 60)),
                'created_at' => Carbon::now()->subDays(rand(0, 30)),
                'updated_at' => Carbon::now()->subDays(rand(0, 10)),
            ]);
            
            // 如果使用默认菜单，创建菜单并初始化菜品
            if ($menuSource === 'default') {
                $menu = Menu::create([
                    'name' => $room->title . '的菜单',
                    'description' => '基于默认菜单创建的菜单',
                    'creator_id' => $room->creator_id,
                    'source_type' => 'custom',
                    'source_id' => null,
                    'is_public' => false,
                    'is_template' => false,
                ]);

                $room->update(['menu_id' => $menu->id]);

                $dishService = app(DishService::class);
                $dishService->initializeMenuDishes($menu);
            }
            
            // 创建者自动加入房间
            RoomMember::create([
                'room_id' => $room->id,
                'user_id' => $creator->id,
                'role' => 'creator',
                'joined_at' => $room->created_at,
                'last_active_at' => $room->last_activity_at,
                'is_active' => true,
                'settings' => [],
                'is_pinned' => false,
                'pin_order' => 0,
            ]);
            
            // 随机添加一些成员
            $memberCount = rand(2, 8);
            $availableUsers = $users->where('id', '!=', $creator->id)->random($memberCount);
            
            foreach ($availableUsers as $user) {
                RoomMember::create([
                    'room_id' => $room->id,
                    'user_id' => $user->id,
                    'role' => 'member',
                    'joined_at' => $room->created_at->addMinutes(rand(1, 60)),
                    'last_active_at' => Carbon::now()->subMinutes(rand(0, 120)),
                    'is_active' => rand(1, 10) <= 8, // 80%活跃
                    'settings' => [],
                    'is_pinned' => rand(1, 10) <= 2, // 20%置顶
                    'pin_order' => rand(0, 10),
                ]);
            }
        }
        
        $this->command->info('已创建 20 个房间数据');
    }
}